﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Fish.Models;
using Fish.DAL;
using System.Security.Cryptography;
using System.Web.Security;
using Microsoft.AspNet.Identity;

namespace Fish.Controllers
{
    /*Used to handle all methods involving the relationship between a user and his events.
     */
    [Authorize]
    public class EventUserRelationsController : Controller
    {
        private FishContext db = new FishContext();

        /*Method to get the user id, this is done either through the session or MVC's Identity object. 
        Redirects to homepage if user is not signed in*/
        public int GetLoggedInID()
        {
            int id = -1;

            if (Session != null)
            {
                if (Session["userID"] != null)
                {
                    id = int.Parse(Session["userID"].ToString());
                }
            }

            else
            {
                if (User.Identity.IsAuthenticated)
                {
                    string username = User.Identity.GetUserName();
                    Users us = db.Users.Where(u => u.Username.Equals(username)).FirstOrDefault();
                    id = us.ID;
                }
                else
                {
                    id = -1;
                    FormsAuthentication.SignOut();
                    RedirectToAction("Index", "Home");
                }
            }
            return id;
        }
        
        //Add a new relationship between a user and an event
        public ActionResult AddGuest()
        {
            int userID = int.Parse(Session["userID"].ToString());
            int eventID = int.Parse(Session["eventID"].ToString());
            EventUserRelations eur = new EventUserRelations();
            eur.UsersID = userID;
            eur.EventsID = eventID;
            eur.AttendingStatus = 0;
            eur.IsAdmin = false;
            db.EventUserRelations.Add(eur);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        // GET: /EventUserRelations/
        public ActionResult Index(int? eventID)
        {
            if (eventID == null) { 
                int id = GetLoggedInID();
                var eventuserrelations = db.EventUserRelations.Include(e => e.Events).Include(e => e.Users).Where(e => e.UsersID == id);
                return View(eventuserrelations.ToList().OrderByDescending(a=>a.Created));
            }
            else
            {
                var eventuserrelations = db.EventUserRelations.Include(e => e.Events).Include(e => e.Users).Where(e => e.EventsID == eventID);
                return View(eventuserrelations.ToList().OrderByDescending(a => a.Created));
            }
        }

        // GET: /EventUserRelations/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            EventUserRelations eventuserrelations = db.EventUserRelations.Find(id);
            if (eventuserrelations == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            System.Diagnostics.Debug.WriteLine("Tasks: " + eventuserrelations.Tasks.IndexOf(eventuserrelations.Tasks.Last()));
            return View(eventuserrelations);
        }

        // GET: /EventUserRelations/Create
        public ActionResult Create()
        {
            ViewBag.EventsID = new SelectList(db.Events, "ID", "Name");
            ViewBag.UsersID = new SelectList(db.Users, "ID", "Username");
            return View();
        }

        // POST: /EventUserRelations/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="ID,EventsID,UsersID,IsAdmin,AttendingStatus,Tasks,Created,Modified")] EventUserRelations eventuserrelations)
        {
            if (ModelState.IsValid)
            {
                db.EventUserRelations.Add(eventuserrelations);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.EventsID = new SelectList(db.Events, "ID", "Name", eventuserrelations.EventsID);
            ViewBag.UsersID = new SelectList(db.Users, "ID", "Username", eventuserrelations.UsersID);
            return View(eventuserrelations);
        }

        // GET: /EventUserRelations/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            EventUserRelations eventuserrelations = db.EventUserRelations.Find(id);
            if (eventuserrelations == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            ViewBag.EventsID = new SelectList(db.Events, "ID", "Name", eventuserrelations.EventsID);
            ViewBag.UsersID = new SelectList(db.Users, "ID", "Username", eventuserrelations.UsersID);
            return View(eventuserrelations);
        }

        // POST: /EventUserRelations/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="ID,EventsID,UsersID,IsAdmin,AttendingStatus,Tasks,Created,Modified")] EventUserRelations eventuserrelations)
        {
            if (ModelState.IsValid)
            {
                db.Entry(eventuserrelations).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.EventsID = new SelectList(db.Events, "ID", "Name", eventuserrelations.EventsID);
            ViewBag.UsersID = new SelectList(db.Users, "ID", "Username", eventuserrelations.UsersID);
            return View(eventuserrelations);
        }

        // GET: /EventUserRelations/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            EventUserRelations eventuserrelations = db.EventUserRelations.Find(id);
            if (eventuserrelations == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(eventuserrelations);
        }

        // POST: /EventUserRelations/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            EventUserRelations eventuserrelations = db.EventUserRelations.Find(id);
            db.EventUserRelations.Remove(eventuserrelations);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
